﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using Microsoft.Reporting.WinForms;
using ReagentStore.ERM;

namespace ReagentStore.Report
{
	public enum ReportTypes
	{
		Expiration,
		Purchase,
		Record,
		Stock
	}

	public partial class ReportForm : Form
	{
		private readonly string _company;
		private readonly Dictionary<ReportTypes, IReport> _dictReport = new Dictionary<ReportTypes, IReport>();
		private readonly ReportTypes _typeReport;

		public ReportForm(ReportTypes type, string company)
		{
			InitializeComponent();
			//reportViewer.SetDisplayMode(DisplayMode.PrintLayout);

			InitializeDictionary();
			_typeReport = type;
			_company = company;

			if (_typeReport == ReportTypes.Record)
				InitializeControlsForRecord();
			else
				groupBox.Visible = false;
		}

		private void InitializeControlsForRecord()
		{
			groupBox.Visible = true;
			dateBegin.Value = DateTime.Today;
			dateEnd.Value = DateTime.Today.AddDays(1);

			using (var db = new ReagentStoreContainer(new ConnectionStringBuilder().EntityConnectionString()))
			{
				List<Reagent> list = db.Reagents.ToList();
				Reagent reagent = Reagent.CreateReagent(0, "所有试剂", string.Empty, 0, 0, 0, 0);
				list.Add(reagent);
				list = list.OrderBy(r => r.ReagentID).ToList();
				comboReagent.DataSource = list;
				comboReagent.DisplayMember = "Name";
				comboReagent.ValueMember = "ReagentID";
			}
		}

		private void InitializeDictionary()
		{
			_dictReport.Add(ReportTypes.Expiration, new ExpirationReport());
			_dictReport.Add(ReportTypes.Purchase, new PurchaseReport());
			_dictReport.Add(ReportTypes.Record, new RecordReport());
			_dictReport.Add(ReportTypes.Stock, new StockReport());
		}

		private void LoadReport()
		{
			try
			{
				IReport report = _dictReport[_typeReport];

				reportViewer.ProcessingMode = ProcessingMode.Local;
				reportViewer.LocalReport.ReportEmbeddedResource = report.ReportPath;

				reportViewer.LocalReport.SetParameters(new ReportParameter("Company", _company));

				if (!report.IsLoaded)
					report.LoadData();

				reportViewer.LocalReport.DataSources.Add(new ReportDataSource("ds" + _typeReport.ToString(), report.ReportData));
			}
			catch (Exception e)
			{
				MessageBox.Show(e.Message);
			}
		}

		private void ReportForm_Load(object sender, EventArgs e)
		{
			LoadReport();
			reportViewer.RefreshReport();
		}

		private void buttonOK_Click(object sender, EventArgs e)
		{
			var report = (RecordReport) _dictReport[ReportTypes.Record];
			report.ReagentID = (int) comboReagent.SelectedValue;
			report.DateBegin = dateBegin.Value;
			report.DateEnd = dateEnd.Value;

			report.LoadData();
			reportViewer.RefreshReport();
		}
	}
}